<template>
  <div class="pagination">
    <span v-if="page > 1 && pages >= page" @click="gotoPage(1)">首页</span>
    <span v-if="page > 1 && pages >= page" @click="gotoPage(page - 1)"
      >上一页</span
    >
    <span v-if="page > 1 && page - 3 >= 1">...</span>

    <span
      v-for="item of showPages"
      :key="item"
      :class="page === item ? `current-page` : ``"
      @click="gotoPage(item)"
      >{{ item }}</span
    >

    <span v-if="page + 3 <= pages">...</span>
    <span v-if="page < pages" @click="gotoPage(page + 1)">下一页</span>
    <span v-if="page < pages" @click="gotoPage(pages)">尾页</span>
  </div>
</template>

<script>
export default {
  name: "Pgination",

  props: {
    pages: {
      type: Number,
      default: 1,
    },

    page: {
      type: Number,
      default: 1,
    },
  },

  methods: {
    gotoPage(n) {
      if (n < 1) {
        this.$emit("changePage", 1);
      } else if (n > this.pages) {
        this.$emit("changePage", this.pages);
      } else this.$emit("changePage", n);
    },
  },

  computed: {
    showPages() {
      let arr = [this.page];
      let prev = this.page;
      let next = this.page;

      let showPagesNumber = 4;

      while (showPagesNumber > 0) {
        if (prev > 1 && showPagesNumber > 0) {
          arr.unshift(--prev);
          showPagesNumber--;
        }
        if (next < this.pages && showPagesNumber > 0) {
          arr.push(++next);
          showPagesNumber--;
        }
        if (prev <= 1 && next >= this.pages) break;
      }

      return arr;
    },
  },
};
</script>

<style>
</style>